package com.wpf.system.controller;

import cn.hutool.core.convert.Convert;
import com.wpf.system.common.response.ResultUtils;
import com.wpf.system.common.response.ResultVO;
import com.wpf.system.entity.vo.CascaderVO;
import com.wpf.system.entity.Menu;
import com.wpf.system.service.MenuService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/api/menu")
public class MenuController {

    @Resource
    private MenuService menuService;

    @PreAuthorize("hasAuthority('sys:menu:list')")
    @GetMapping("/list")
    public List<Menu> getMenuList(){
        return menuService.getMenuList();
    }

    @GetMapping("/plist")
    public List<CascaderVO> getParentMenuList(){
        return menuService.getParentMenuList();
    }

    @PreAuthorize("hasAuthority('sys:menu:add')")
    @PostMapping
    public ResultVO addMenu(@RequestBody Menu menu){
        boolean flag = menuService.save(menu);
        if (flag){
            return ResultUtils.success("添加功能成功！");
        }else{
            return ResultUtils.error("添加功能失败！");
        }
    }

    @PreAuthorize("hasAuthority('sys:menu:edit')")
    @PutMapping
    public ResultVO editMenu(@RequestBody Menu menu){
        boolean flag = menuService.updateById(menu);
        if (flag){
            return ResultUtils.success("修改功能成功！");
        }else{
            return ResultUtils.error("修改功能失败！");
        }
    }

    @PreAuthorize("hasAuthority('sys:menu:edit')")
    @PutMapping("/status")
    public ResultVO editMenuStatus(@RequestBody Long id){
        boolean flag = Convert.toBool(menuService.editMenuStatusById(id));
        if (flag){
            return ResultUtils.success("修改功能状态成功！");
        }else{
            return ResultUtils.error("修改功能状态失败！");
        }
    }

    @PreAuthorize("hasAuthority('sys:menu:delete')")
    @DeleteMapping("/{id}")
    public ResultVO deleteMenu(@PathVariable("id") Long id){
        // 递归删除子菜单
        if (menuService.deleteMenuByd(id)){
            return ResultUtils.success("删除功能成功！");
        }else{
            return ResultUtils.error("删除功能失败！");
        }
    }
}
